package com.ruoyi.until;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rabbitmq.client.Channel;
import com.ruoyi.pojo.Order;
import com.ruoyi.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.util.Date;

/**
 * @author: liufei
 * @Desc:
 * @create: 2024-11-07 13:06
 **/
@Configuration
public class Rabbit {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = "dlxQueue")
    public void dlk(String msg, Message messagem, Channel channel) throws IOException {
        System.out.println("订单ID:"+msg);

        System.out.println("消费时间:"+new Date());
        try {

            String s = stringRedisTemplate.opsForValue().get("orderId:" + msg);
            if(StringUtils.isEmpty(s)){
                System.out.println("订单不存在");
                channel.basicNack(messagem.getMessageProperties().getDeliveryTag(), false, true);
            }

            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getOrderId, s);
            Order one = orderService.getOne(wrapper);
            //延迟队列模拟十分钟订单未支付，自动关闭
            if(one.getOrderStatus().equals("已接单")){
                LambdaUpdateWrapper<Order> wrapper1 = new LambdaUpdateWrapper<>();
                wrapper1.eq(Order::getOrderId, s).set(Order::getOrderStatus, "订单关闭");
                System.out.println("超时未支付，订单关闭");
                orderService.update(wrapper1);
            }

            stringRedisTemplate.delete("orderId:" + msg);
            channel.basicAck(messagem.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(messagem.getMessageProperties().getDeliveryTag(), false, true);
            throw new RuntimeException(e);
        }

    }


}
